package com.mcptt.db.op;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import com.cloudptt.api.product.log.Log;
import com.mcptt.db.DBProvider;
import com.mcptt.db.DbConst;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class AddrDbOperator {

	public static String THIS_FILE = "AddressDbOperator";
	private Context ctx = null;

	public AddrDbOperator(Context ctx)
	{
		this.ctx = ctx;
		cleanAllLogin();
	}
	
	public List<GroupInfo> getGroupList()
	{
		Log.debug(this.getClass(), "getGroupList");
		ContentResolver cr = ctx.getContentResolver();
		List<GroupInfo> list = new Vector<GroupInfo>();
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, null,
					null, DbConst.COL_GroupId );

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext()) 
			{  
				GroupInfo info = new GroupInfo(cursor);  
				list.add(info);
			} 
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getGroupList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		Log.debug(this.getClass(), "getGroupList list = " + list);
		return list;
	}

	public List<AddrInfo> getGroupAddrList()
	{
		Log.debug(this.getClass(), "getGroupAddrList");
		ContentResolver cr = ctx.getContentResolver();
		List<AddrInfo> list = new Vector<AddrInfo>();
		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, null,
					null, DbConst.COL_GroupId );

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext())
			{
				GroupInfo info = new GroupInfo(cursor);
				list.add(info);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getGroupList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}
	
	public List<GroupInfo> getGroupListAndUserList()
	{
		Log.debug(this.getClass(), "getGroupListAndUserList");
		ContentResolver cr = ctx.getContentResolver();
		List<GroupInfo> list = new Vector<GroupInfo>();
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, null,
					null, DbConst.COL_GroupId + " DESC");

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext()) 
			{  
				GroupInfo info = new GroupInfo(cursor);  
//				Log.d(THIS_FILE, "onLoadFinished info = " + info);
				
//				String groupMcId = info.getMcId();
//				List<UserInfo> userList = getNewAddressList(groupMcId);
//				String num = "rtsp://admin:Lhp963852@192.168.101.64:554/h264/ch1/main/av_stream";
//				UserInfo userInfo = new UserInfo(AddrInfo.UserType_Camera,"camera_1",num,groupMcId);
//				userList.add(userInfo);
				
//				info.setUserList(userList);
				
				list.add(info);
			} 
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getGroupList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}

	public List<AddrInfo> getAddrList(String pGroupId)
	{
		Log.debug(this.getClass(), "getGroupListAndUserList pGroupId = " + pGroupId);
		Log.d(THIS_FILE, "getAddrList pGroupId = " + pGroupId);
		ContentResolver cr = ctx.getContentResolver();
		List<AddrInfo> list = new Vector<AddrInfo>();

		List<UserInfo> userList = getNewAddressList(pGroupId);
		for(Iterator<UserInfo> itor = userList.iterator();itor.hasNext();)
		{
			UserInfo info = itor.next();
//			Log.d(THIS_FILE, "getAddrList info = " + info);
			list.add(info);
		}

		Cursor cursor = null;
		try
		{
			String selection = null;
			if(pGroupId != null)
			{
				selection = DbConst.COL_PGroupId + "='" + pGroupId+"'";
			}
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, selection,
					null, null);

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
//				Log.d(THIS_FILE, "getAddrList cursor.getCount() = " + cursor.getCount());
				return list;
			}
			while (cursor.moveToNext())
			{
				GroupInfo info = new GroupInfo(cursor);
//				Log.d(THIS_FILE, "getAddrList info = " + info);
				list.add(info);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getAddrList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}

	public List<UserInfo> getAddressList()
	{
		Log.debug(this.getClass(), "getAddressList");
		ContentResolver cr = ctx.getContentResolver();

//		String selection = DbConst.COL_UserType + "=?";
////		String selection = DbConst.COL_UserType + "= " + addrType;
//		if(addrType == UserInfo.UserType_User)
//		{
//			selection =  DbConst.COL_UserType + " = "+ UserInfo.UserType_Dac + "  or "  + selection;
//		}

		List<UserInfo> list = new Vector<UserInfo>();

		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.ADDRESS_URI,
					DBProvider.ADDRESS_FULL_PROJECTION, null,
					null, DbConst.COL_GroupId );

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext())
			{
				UserInfo info = new UserInfo(cursor);
				list.add(info);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getAddressList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}

	public List<AddrInfo> getUsrAddressList()
	{
		Log.debug(this.getClass(), "getUsrAddressList");
		ContentResolver cr = ctx.getContentResolver();

//		String selection = DbConst.COL_UserType + "=?";
////		String selection = DbConst.COL_UserType + "= " + addrType;
//		if(addrType == UserInfo.UserType_User)
//		{
//			selection =  DbConst.COL_UserType + " = "+ UserInfo.UserType_Dac + "  or "  + selection;
//		}

		List<AddrInfo> list = new Vector<AddrInfo>();

		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.ADDRESS_URI,
					DBProvider.ADDRESS_FULL_PROJECTION, null,
					null, DbConst.COL_State + " DESC");

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext())
			{
				UserInfo info = new UserInfo(cursor);
//				Log.debug(this.getClass(), "getUsrAddressList info = " + info);
				if(!hasThisUser(list,info)) {
//					Log.debug(this.getClass(), "getUsrAddressList hasThisUser info = " + info);
					list.add(info);
				}
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getAddressList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}

	public List<AddrInfo> getUsrAddressList(String groupMcId)
	{
		Log.debug(this.getClass(), "getUsrAddressList groupMcId = " + groupMcId);
		ContentResolver cr = ctx.getContentResolver();
		String selection = null;// + " and " + DbConst.COL_State + " = 1";;
		if( groupMcId != null)
		{
			selection = DbConst.COL_GroupId + " = " + groupMcId;
		}
		List<AddrInfo> list = new Vector<AddrInfo>();

//		Log.debug(this.getClass(), "getNewAddressList selection = " + selection);

		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.LOGIN_URI,
					DBProvider.LOGIN_STATE_FULL_PROJECTION, selection,
					null, DbConst.COL_GroupId);

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
//			Log.debug(this.getClass(),"onLoadFinished Cursor.getCount() = " + cursor.getCount());
			while (cursor.moveToNext())
			{
				UserInfo info = new UserInfo(cursor);
				list.add(info);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getNewAddressList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}

	private boolean hasThisUser(List<AddrInfo> list,UserInfo info)
	{
		for(Iterator<AddrInfo> itor = list.iterator();itor.hasNext();)
		{
			AddrInfo newInfo = itor.next();
			if(newInfo.isSameOne(info))
			{
				return true;
			}
		}
		return false;
	}
	
	public List<UserInfo> getNewAddressList(String groupMcId)
	{
		Log.debug(this.getClass(), "getNewAddressList groupMcId = " + groupMcId);
		ContentResolver cr = ctx.getContentResolver();
		String selection = null;// + " and " + DbConst.COL_State + " = 1";;
		if( groupMcId != null)
		{
			selection = DbConst.COL_GroupId + " = " + groupMcId;
		}
		List<UserInfo> list = new Vector<UserInfo>();

//		Log.debug(this.getClass(), "getNewAddressList selection = " + selection);
		
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.LOGIN_URI,
					DBProvider.LOGIN_STATE_FULL_PROJECTION, selection,
					null, DbConst.COL_GroupId);

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
//			Log.debug(this.getClass(),"onLoadFinished Cursor.getCount() = " + cursor.getCount());
			while (cursor.moveToNext()) 
			{  
				UserInfo info = new UserInfo(cursor);  
				list.add(info);
			} 
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getNewAddressList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}
	
	public List<UserInfo> getNewAddressList(String groupMcId,String mcId)
	{
		Log.debug(this.getClass(), "getNewAddressList groupMcId = " + groupMcId + " mcId = " + mcId);
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_GroupId + " = " + groupMcId;
		if(mcId != null)
		{
			selection = selection + " and id <> " + mcId ;//+ " and " + DbConst.COL_State + " = 1";
		}
		List<UserInfo> list = new Vector<UserInfo>();

//		Log.debug(this.getClass(), "getNewAddressList selection = " + selection);
		
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.LOGIN_URI,
					DBProvider.LOGIN_STATE_FULL_PROJECTION, selection,
					null, DbConst.COL_GroupId);

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
//			Log.debug(this.getClass(),"onLoadFinished Cursor.getCount() = " + cursor.getCount());
			while (cursor.moveToNext()) 
			{  
				UserInfo info = new UserInfo(cursor);  
				list.add(info);
			} 
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getNewAddressList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}
	
	public GroupInfo findGroupByUId(String mcId)
	{
		GroupInfo info = null;
		ContentResolver cr = ctx.getContentResolver();				
		String selection = DbConst.COL_Id  + " =?";
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI, DBProvider.GROUP_ADDRESS_FULL_PROJECTION, selection, new String[]{mcId}, null);	
			if(cursor !=null
					&& cursor.getCount() > 0)
			{			
				if(cursor.moveToFirst())
				{
					info = new GroupInfo(cursor);
				}
			}
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "findGroupByUId e = " + e);
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return info;
	}

	public UserInfo findUserByNum(int addrType,String mcId)
	{
		UserInfo info = null;
		ContentResolver cr = ctx.getContentResolver();				
		String selection =  DbConst.COL_Id  + " =?";
//		String selection =  DbConst.COL_UserType +" = " + addrType + " and "+ DbConst.COL_McId  + " =?";
//		if(addrType == UserInfo.UserType_User)
//		{
//			selection =  DbConst.COL_UserType + " = "+ UserInfo.UserType_Dac + "  or "  + selection;
//		}
		Log.debug(this.getClass(), "findGroupByUId selection = " + selection);
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.ADDRESS_URI, DBProvider.ADDRESS_FULL_PROJECTION, selection, new String[]{mcId}, null);	

			if(cursor !=null
					&& cursor.getCount() > 0)
			{			
				if(cursor.moveToFirst())
				{
					info = new UserInfo(cursor);
				}
			}
		} 
		catch (Exception e) 
		{
			Log.debug(this.getClass(), "findUserByNum e = " + e);
			// TODO: handle exception
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return info;
	}

	public void addGroup(GroupInfo info)
	{
//		Log.debug(this.getClass(), "addGroup info = " + info);
		String mcId = info.getMcId();
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_Id + "=?";	

		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, selection,
					new String[] {mcId}, null);
			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				Uri uri = cr.insert(DbConst.GROUP_ADDRESS_URI, info.getContentValues());
//				Log.debug(this.getClass(), "addGroup uri = " + uri);
			}
		} 
		catch (Exception e) 
		{
			Log.debug(this.getClass(), "addGroup e = " + e);
			// TODO: handle exception
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
	}
	
	public void addUser(UserInfo info)
	{
//		Log.debug(this.getClass(), "addUser info = " + info);
		String mcId = info.getMcId();
		ContentResolver cr = ctx.getContentResolver();
		
		String selection =  DbConst.COL_GroupId +" = " + info.getGroupId() + " and "+ 
                DbConst.COL_Id  + " =?";

		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.ADDRESS_URI,
					DBProvider.ADDRESS_FULL_PROJECTION, selection,
					new String[] {mcId}, null);
			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				Uri uri = cr.insert(DbConst.ADDRESS_URI, info.getContentValues());
//				Log.debug(this.getClass(), "addUser uri = " + uri);
			}
		} 
		catch (Exception e) 
		{
			Log.debug(this.getClass(), "addUser e = " + e);
			// TODO: handle exception
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
	}
	
	public void updateGroup(GroupInfo info)
	{
		String mcId = info.getMcId();
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_Id + "=?";
		int ret = cr.update(DbConst.ADDRESS_URI, info.getContentValues(), selection, new String[] { mcId });
		if(ret <= 0)
		{
			addGroup(info);
		}
	}
	private void updateUser(int mcType,UserInfo info)
	{
//		Log.debug(this.getClass(), "updateUser mcType = " + mcType + "info = " + info);
		String mcId = info.getMcId();
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_GroupId +" = " + info.getGroupId() + " and "+ 
                DbConst.COL_Id  + " =?";
		int ret = cr.update(DbConst.ADDRESS_ID_URI_BASE, info.getUpdateContentValues(mcType), selection, new String[] { mcId });
		if(ret <= 0)
		{
			addUser(info);
		}
	}
	
	public void updateGroupName(String num,String name)
	{
//		Log.debug(this.getClass(), "updateUser num = " + num + " name = " + name);
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_GroupId + "='" + num  + "'";
		int ret = cr.update(DbConst.GROUP_ADDRESS_ID_URI_BASE, GroupInfo.getUpdateContentValues(name), selection, null);
		if(ret <= 0)
		{
			Log.debug(this.getClass(), "updateGroupName failed" );
		}
	}
	
//	public void clearDefaultGroupInfo()
//	{
//		Log.debug(this.getClass(), "clearDefaultGroupInfo");
//		ContentResolver cr = ctx.getContentResolver();
//		String selection = DbConst.COL_Type + "=" + GroupInfo.GroupType_Default;
//		int ret = cr.update(DbConst.GROUP_ADDRESS_ID_URI_BASE, GroupInfo.getClearDefaultGroupInfoContentValues(), selection, null);
//		if(ret <= 0)
//		{
//			Log.debug(this.getClass(), "updateGroupName failed" );
//		}
//	}
//	
//	public void setDefaultGroupInfo(GroupInfo info)
//	{
//		Log.debug(this.getClass(), "setDefaultGroupInfo info = " + info);
//		if(info == null)
//		{
//			return;
//		}
//		ContentResolver cr = ctx.getContentResolver();
//		String groupNum = info.getGroupNum();
//		String selection = DbConst.COL_GroupId + "='" + groupNum  + "'";
//		int ret = cr.update(DbConst.GROUP_ADDRESS_ID_URI_BASE, GroupInfo.getDefaultGroupInfoContentValues(), selection, null);
//		if(ret <= 0)
//		{
//			Log.debug(this.getClass(), "updateGroupName failed" );
//		}
//	}
	
	public void deleteAllGroupUser()
	{
//		Log.debug(this.getClass(), "deleteAllGroupUser");
		ContentResolver cr = ctx.getContentResolver();
		cr.delete(DbConst.GROUP_ADDRESS_URI, null,null);
	}
	public void deleteUser(UserInfo info)
	{
//		Log.debug(this.getClass(), "deleteUser");
		String mcId = info.getMcId();

		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_Id + "=?";
		cr.delete(DbConst.ADDRESS_URI, selection,
				new String[] { mcId });
	}
	public void deleteAllUser()
	{
//		Log.debug(this.getClass(), "deleteAllUser");
		ContentResolver cr = ctx.getContentResolver();
		cr.delete(DbConst.ADDRESS_URI, null,null);
	}
	public void cleanAllLogin()
	{
//		Log.i(THIS_FILE,"cleanAllLogin");
		ContentResolver cr = ctx.getContentResolver();
		cr.delete(DbConst.LOGIN_URI, "1=1", null);
		cr.delete(DbConst.MAP_POINT_URI, "1=1", null);
	}
}
